use {
    crate::model::dapp_contract::DAppContract,
    sqlx::{MySql, Pool, Row},
};

impl DAppContract {
    pub fn from(chain: String, pr: String, addr: String) -> Self {
        DAppContract {
            id: None,
            chain,
            pr: Some(pr),
            addr,
        }
    }

    pub async fn insert(one: &Self, pool: &Pool<MySql>) -> anyhow::Result<u64> {
        let id = sqlx::query(r#"INSERT INTO dapp_contract(chain, pr, addr) VALUES (?,?,?)"#)
            .bind(one.chain.clone())
            .bind(one.pr.clone())
            .bind(one.addr.clone())
            .execute(pool)
            .await?
            .last_insert_id();
        Ok(id)
    }

    pub async fn select_all(chain: &str, pool: &Pool<MySql>) -> anyhow::Result<Vec<DAppContract>> {
        let rows = sqlx::query(r#"SELECT * FROM dapp_contract where `chain` = ? order by id desc"#)
            .bind(chain.to_string())
            .fetch_all(pool)
            .await?;

        let mut list = Vec::new();
        for row in rows {
            let id = row.get::<u64, _>("id");
            let chain = row.get::<String, _>("chain");
            let pr = row.get::<Option<String>, _>("pr");
            let addr = row.get::<String, _>("addr");
            let aw = DAppContract {
                id: Some(id),
                chain,
                pr,
                addr,
            };
            list.push(aw);
        }

        Ok(list)
    }
}
